<template>
  <div class="paper">
    <el-table :data="paperInfo.arr" border v-loading="loading">
      <el-table-column prop="id" label="题库编号" width="180"></el-table-column>
      <el-table-column prop="paperName" label="题库名称" width="180"></el-table-column>
      <el-table-column prop="paperDate" label="题库创建日期" width="120"></el-table-column>
      <el-table-column prop="paperCreator" label="题库创建者" width="120"></el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button @click="lookPaper(scope.row)" type="primary" size="small">查看试题</el-button>
          <el-button @click="editPaper(scope.$index,scope.row)" type="primary" size="small">修改题库</el-button>
          <el-button @click="deletePaper(scope.row)" type="danger" size="small">删除题库</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          :current-page="pagination.pageNum"
          :page-sizes="[3, 6, 9, 12]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-config-provider>
    <el-dialog
        title="编辑试卷信息"
        v-model="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <section class="update">
        <el-form ref="changPaperRef" :model="paperInfo.edit" label-width="80px">
          <el-form-item label="题库编号" label-width="100px">
            <el-input v-model="paperInfo.edit.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="题库名称"
                        label-width="100px"
                        prop="paperName"
                        :rules="[{required: true, message: '题库名称不能为空', trigger: 'change'}]">
            <el-input v-model="paperInfo.edit.paperName"></el-input>
          </el-form-item>
          <el-form-item label="创建日期"
                        label-width="100px"
                        prop="paperDate"
                        v-if="role === '0'"
                        :rules="[{required: true, message: '题库创建日期不能为空', trigger: 'change'}]">
            <el-col :span="11">
              <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="paperInfo.edit.paperDate"
                  style="width: 100%;">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-space fill v-if="role === '1'">
            <el-alert type="info" show-icon :closable="false">
              <p>创建日期系统自动生成，且不能修改，若想修改请联系管理员</p>
            </el-alert>
            <el-form-item label="创建日期" label-width="100px">
              <el-col :span="11">
                <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="paperInfo.edit.paperDate"
                    style="width: 100%;"
                    disabled>
                </el-date-picker>
              </el-col>
            </el-form-item>
          </el-space>

          <el-form-item label="创建者编号"
                        prop="paperCreator"
                        v-if="role === '0'"
                        label-width="100px"
                        :rules="[{required: true, message: '题库创建者不能为空', trigger: 'change'}]">
            <el-input v-model="paperInfo.edit.paperCreatorId"></el-input>
          </el-form-item>
          <el-form-item label="创建者"
                        prop="paperCreator"
                        label-width="100px"
                        v-if="role === '0'"
                        :rules="[{required: true, message: '题库创建者不能为空', trigger: 'change'}]">
            <el-input v-model="paperInfo.edit.paperCreator"></el-input>
          </el-form-item>

          <el-space fill v-if="role === '1'">
            <el-alert type="info" show-icon :closable="false">
              <p>创建者默认为自己，且不能修改，若想修改请联系管理员</p>
            </el-alert>
            <el-form-item label="创建者" label-width="100px">
              <el-input v-model="paperInfo.edit.paperCreator" disabled></el-input>
            </el-form-item>
          </el-space>
        </el-form>
      </section>
      <template v-slot:footer>
        <el-button @click="editBack()">取 消</el-button>
        <el-button type="primary" @click="editSubmit()">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getCurrentInstance, onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import AES from "@/utils/AESUtil";
import {isObjectValueEqual} from "@/utils/funUtils";
import {useRouter} from "vue-router/dist/vue-router";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
export default {
  name: "selectPaper",
  setup(){
    const {proxy} = getCurrentInstance()
    const router = useRouter()
    let changPaperRef = ref(null)
    let loading = ref(false) //加载标识符
    let dialogVisible = ref(false)
    // eslint-disable-next-line no-undef
    let role = ref(AES.Decrypt($cookies.get("role")))
    let paperInfo = reactive({
      arr: [],
      edit: {},
      editIndex: null,
    })
    let pagination = reactive({
      pageNum: 1, //当前页
      total: Number(''), //记录条数
      pageSize: 3 //每页条数
    })
    onMounted(()=>{
      getPaperInfo()
    })
    function getPaperInfo(){
      loading.value = true
      proxy.$axios.get(
          `/manage/paper/${pagination.pageNum}/${pagination.pageSize}`
      ).then(
          response => {
            paperInfo.arr = [...response.data.list]
            pagination.total = response.data.total
            pagination.pageNum = response.data.pageNum
            pagination.pageSize = response.data.pageSize
            loading.value = false
          },
          error => {
            console.log('请求失败', error.message)
          }
      )
    }
    function pageSizeChange(value){//改变当前记录条数
      pagination.pageSize = value
      getPaperInfo()
    }
    function pageNumChange(value){//改变当前页码
      pagination.pageNum = value
      getPaperInfo()
    }
    function handleClose(done){
      ElMessageBox.confirm('确认关闭？',"",
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        done();
        ElMessage({
          type: 'info',
          message: '取消修改',
        })
      }).catch(() => {});
    }
    function lookPaper(value){
      if (role.value === '1'){
        // eslint-disable-next-line no-undef
        if ($cookies.get("id") !== value.paperCreatorId.toString()){
          ElMessage({
            type: 'error',
            message: '您无权查看他人题库',
          })
          return
        }
      }
      router.push({path:"/lookPaperAnswer",query:{id: value.id}})
      proxy.$bus.emit('sendData',value.paperName)
    }
    function editPaper(index,value){
      if (role.value === '1'){
        // eslint-disable-next-line no-undef
        if ($cookies.get("id") !== value.paperCreatorId.toString()){
          ElMessage({
            type: 'error',
            message: '您无权修改他人题库',
          })
          return
        }
      }
      dialogVisible.value = true
      paperInfo.editIndex = index
      paperInfo.edit = {...value}
    }
    function editSubmit(){
      proxy.$refs.changPaperRef.validate((valid) => {
        if (valid) {
          if (isObjectValueEqual(paperInfo.arr[paperInfo.editIndex],paperInfo.edit)){
            ElMessage({
              type: 'info',
              message: '信息没有改动',
            })
            return false
          }
          proxy.$axios.put(
              // eslint-disable-next-line no-undef
              `/manage/paper/update`,
              {...paperInfo.edit}
          ).then(
              response => {
                if (response.data) {
                  ElMessage({
                    type: 'success',
                    message: '修改成功',
                  })
                  dialogVisible.value = false
                  getPaperInfo()
                }
              },
              error => {
                console.log('请求失败', error.message)
              }
          )
        }else {
          return false
        }
      })
    }
    function editBack(){
      dialogVisible.value = false
      ElMessage({
        type: 'info',
        message: '取消修改',
      })
      proxy.$refs.changPaperRef.clearValidate()
    }
    function deletePaper(value) {
      if (role.value === '1'){
        // eslint-disable-next-line no-undef
        if ($cookies.get("id") !== value.paperCreatorId.toString()){
          ElMessage({
            type: 'error',
            message: '您无权删除他人题库',
          })
          return
        }
      }
      ElMessageBox.confirm(
          '是否永久删除该考试信息,该操作不可逆！！！',
          '警告',
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        proxy.$axios.delete(`/manage/paper/delete/${value.id}`).then(
            response => {
              if (response.data){
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getPaperInfo()
              }
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
    }
    return{
      loading,
      paperInfo,
      pagination,
      dialogVisible,
      changPaperRef,
      role,
      pageSizeChange,
      pageNumChange,
      handleClose,
      lookPaper,
      editPaper,
      editBack,
      editSubmit,
      deletePaper,
      zhCn
    }
  }
}
</script>

<style scoped>
.paper {
  padding: 0px 40px;
}
.paper .page {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.paper .edit{
  margin-left: 20px;
}

</style>